package q0020;

import java.util.Stack;

/**
 * @author wangxiyue@cyou-inc.com
 * @date 2019-09-04
 * @since 1.0.0
 */
public class Solution {

    public boolean isValid(String s) {
        if (null == s) {
            return true;
        }
        char[] chars = s.toCharArray();

        Stack<Character> stack = new Stack();

        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '{') {
                stack.push(chars[i]);
            }
            if (chars[i] == '}') {
                if (!stack.isEmpty() && stack.peek() == '{') {
                    stack.pop();
                } else {
                    return false;
                }
            }
            if (chars[i] == '(') {
                stack.push(chars[i]);
            }
            if (chars[i] == ')') {
                if (!stack.isEmpty() && stack.peek() == '(') {
                    stack.pop();
                } else {
                    return false;
                }
            }
            if (chars[i] == '[') {
                stack.push(chars[i]);
            }
            if (chars[i] == ']') {
                if (!stack.isEmpty() && stack.peek() == '[') {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }

        if (stack.isEmpty()) {
            return true;
        }

        return false;
    }

    public static void main(String[] args) {

        System.out.println("true==" + new Solution().isValid("()"));
        System.out.println("true==" + new Solution().isValid("()[]{}"));
        System.out.println("false==" + new Solution().isValid("(]"));
        System.out.println("false==" + new Solution().isValid("([)]"));
        System.out.println("true==" + new Solution().isValid("{[]}"));


    }
}
